<template>
  <div>
    <Menu menuActive="/faq" />
    <layout>
      <template v-slot:main>
        <el-row :gutter="20">
          <el-col :lg="18" style="margin-bottom: 20px;">
            <div class="faq_detail_info_and_comment_container">
              <div class="faq_detail_info_wrapper height_light_bgcolor" v-loading="infoLoading"
                element-loading-text="正在玩命加载中...">
                <div class="faq_detail_title">
                  <div style="display: flex;align-items: center;">
                    <Avatar :avatarImgUrl="detailData.data.user?.avatar" :nick-name="detailData.data.user?.nickName"
                      :remark="detailData.data.user?.remark" :interestValue="detailData.data.user?.interestValue"
                      :userId="detailData.data.user?.userId" :noteNum="detailData.data.user?.noteNum" :likeNum="detailData.data.user?.likeNum" :followNum="detailData.data.user?.followNum"/>
                    <p class="cursor_class" @click="handleClickToUserBlog(detailData.data.user?.userId)">{{
                        detailData.data.user?.nickName
                    }}</p>
                    <el-button round type="primary" size="small" :loading="fllowbtnLoading"
                      v-if="detailData.data.user?.followType !== 3 && detailData.data.user?.followType == 1"
                      @click="handleClickFollow(0, detailData.data.user?.userId)">关注</el-button>
                    <el-button round size="small" :loading="fllowbtnLoading"
                      v-if="detailData.data.user?.followType !== 3 && detailData.data.user?.followType == 0"
                      @click="handleClickFollow(1, detailData.data.user?.userId)">已关注</el-button>
                    <el-button round size="small" :loading="fllowbtnLoading"
                      v-if="detailData.data.user?.followType !== 3 && detailData.data.user?.followType == 2"
                      @click="handleClickFollow(1, detailData.data.user?.userId)">互相关注</el-button>
                  </div>
                  <div style="display: flex;">
                    <span>{{ detailData.data.createTime }}</span>
                    <!-- <span>采纳率: 100%</span> -->
                  </div>
                </div>
                <h1 class="faq_tit">
                  {{ detailData.data.title }}
                </h1>
                <div class="tag_wrapper">
                  <template v-if="detailData.data.tags">
                    <el-tag v-for="item in detailData.data.tags.split(',')" class="" style="margin-right:10px">{{ item
                    }}</el-tag>
                  </template>
                </div>
                <div class="faq_content" v-html="detailData.data.content">
                </div>
                <div class="ask_issue_tool">
                  <div class="left_tool">
                    <el-button type="primary" :icon="EditPen" @click="handleClickScrollTo">写回答</el-button>
                  </div>
                  <div class="right_tool">
                    <div class="esb_item">
                      <el-icon>
                        <View />
                      </el-icon>
                      <span>{{ detailData.data.pageViewNum }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="faq_comment_wrapper height_light_bgcolor">
                <div class="as_tit">
                  <h1>{{ answerListData.total.value }}条回答</h1>
                  <div>
                    <el-radio-group v-model="radio1" @change="handleChangeRadio">
                      <el-radio-button label="默认" />
                      <el-radio-button label="最新" />
                    </el-radio-group>
                  </div>
                </div>
                <el-card class="isanswer_card" shadow="never" v-if="detailData.data.answerId">
                  <template #header>
                    <div class="card-header">
                      <span class="card_title"><el-icon color="#ffba00" style="margin-right:8px">
                          <StarFilled />
                        </el-icon>采纳的回答</span>
                    </div>
                  </template>
                  <div class="answer_wrapper">
                    <div class="answer_item">
                      <div class="top_answer_auhor_info">
                        <Avatar :avatar-img-url="detailData.data.user?.avatar"
                          :nick-name="detailData.data.user?.nickName" :remark="detailData.data.user?.remark"
                          :interestValue="detailData.data.user?.interestValue" :userId="detailData.data.user?.userId" :noteNum="detailData.data.user?.noteNum" :likeNum="detailData.data.user?.likeNum" :followNum="detailData.data.user?.followNum"/>
                        <p>
                          <span>
                            {{ detailData.data.user?.nickName }}
                          </span>
                          <span class="text_muted">{{ detailData.data.createTime }}</span>
                        </p>
                      </div>
                      <div style="padding: 20px 0 0 50px;word-break: break-all;"
                        v-html="detailData.data.adoptAnwser?.content"></div>
                    </div>
                  </div>
                </el-card>
                <div class="answer_wrapper" v-loading="answerLoading" element-loading-text="正在玩命加载中...">
                  <div class="answer_item" v-for="item in answerListData.data.value">
                    <div class="top_answer_auhor_info">
                      <Avatar :avatar-img-url="item.user?.avatar" :nick-name="item.user?.nickName"
                        :remark="item.user?.remark" :interestValue="item.user?.interestValue" :noteNum="item.user?.noteNum" :likeNum="item.user?.likeNum" :followNum="item.user?.followNum"/>
                      <p>
                        <span>
                          {{ item.user.nickName }}
                        </span>
                        <span class="text_muted">{{ item.createTime }}</span>
                      </p>
                    </div>
                    <div class="bottom_answer_content" v-html="item.content">
                    </div>
                    <div class="thumb_wrap">
                      <el-button type="primary" link @click="handleClickLikeAnswer(item.id, item.faqId)"
                        :loading="likeLading"
                        v-if="!detailData.data.answerId && userInfoState.userId === detailData.data.userId">
                        👍 采纳
                      </el-button>
                    </div>
                  </div>
                  <el-empty description="暂无回答😁~" v-if="!answerLoading && answerListData.total.value <= 0" />
                  <div class="pagination_container">
                    <el-pagination v-model:current-page="searchParams.pageNum" v-model:page-size="searchParams.pageSize"
                      background layout="total, prev, pager, next, jumper" :total="answerListData.total.value"
                      v-if="answerListData.total.value > 0" @current-change="handleCurrentChange" />
                  </div>
                </div>
                <!--富文本编辑器插件区域 -->
                <div class="markdown_edit_content" id="answer">
                  <editor v-model="contents" :min-height="500" :height="500" />
                </div>
                <div class="btn_tol_wrap">
                  <el-button type="primary" style="width:300px" :loading="answerLoadingBtn"
                    @click="handleClickSubmit">提交</el-button>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :lg="6">
            <el-card class="box-card" shadow="never">
              <template #header>
                <div class="card_header">
                  <span style="font-size:16px">7日采纳榜</span>
                </div>
              </template>
              <div class="card_content" v-loading="topLoading" element-loading-text="正在玩命加载中..."
                :style="{ padding: topLoading ? '45px 0' : '' }">
                <div class="caina_item" v-for="(item, index) in topData" :key="item.userId">
                  <div class="left_caina_author_info">
                    <div class="num">{{ index + 1 }}</div>
                    <div class="ava_name" @click="handleClickToUserBlog(item.userId)">
                      <el-avatar :size="30" class="cursor_class" :src="proxy.$baseImgUrl + item.avatar"></el-avatar>
                      <span class="names cursor_class">{{ item.nickName }}</span>
                    </div>
                  </div>
                  <div class="caina_num">{{ (item.adoptionRate * 100).toFixed(0) }}%</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
    </layout>
    <Footer />
  </div>
</template>

<script lang="ts" setup>
import Menu from '@/components/Menu/index.vue'
import Layout from '@/components/Layout/index.vue'
import Footer from '@/components/Footer/index.vue'
import Avatar from '@/components/Avatar/index.vue'
import {
  Tickets,
  UserFilled,
  RefreshLeft,
  Plus,
  Document,
  User,
  ChatDotSquare,
  View,
  Timer,
  Pointer,
  More,
  Location,
  Link,
  OfficeBuilding,
  EditPen,
  StarFilled
} from '@element-plus/icons-vue'
import router from '@/router'
import { computed, getCurrentInstance, onMounted, reactive, ref, toRefs, watch } from 'vue'
import { getFaqDetail, getFaqDetailAnswer, answerQuestion, likeAnswer, getLikeTop } from '@/api/faq'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useStore } from "vuex";
import { followUser } from '@/api/user'
import editor from '@/components/QuillEditor/index.vue'
const { proxy } = getCurrentInstance()
const store = useStore();
const radio1 = ref('默认')
const Route = useRoute();
const id = Route.params.id as string
const detailData = reactive<any>({ data: { user: {} } })
const infoLoading = ref<boolean>(false)
const contents = ref<string>('')
const answerLoadingBtn = ref<boolean>(false)
const searchParams = {
  pageNum: 1,
  pageSize: 5,
}
const answerLoading = ref<boolean>(false)
const answerListData = toRefs(reactive<any>({
  data: [],
  total: 0
}))
const likeLading = ref<boolean>(false)
const topLoading = ref<boolean>(false)
const topData = ref<any>([])
const userInfoState = computed(() => store.state.userInfo);
const fllowbtnLoading = ref<boolean>(false)
// 获取详情数据
const getFaqDetailData = async () => {
  if (!id) {
    return ElMessage({
      message: '获取详情ID失败',
      type: 'error',
      duration: 2 * 1000
    })
  }
  try {
    infoLoading.value = true
    const { data }: any = await getFaqDetail({ id })
    detailData.data = data
  } finally {
    infoLoading.value = false
  }
}
const getFaqDetailAnswerData = async (cate?: any) => {
  if (!id) {
    return ElMessage({
      message: '获取详情ID失败',
      type: 'error',
      duration: 2 * 1000
    })
  }
  try {
    answerLoading.value = true
    const { rows, total }: any = await getFaqDetailAnswer({ ...searchParams, faqId: id, ...cate })
    answerListData.data.value = rows
    answerListData.total.value = total
  } finally {
    answerLoading.value = false
  }
}
const handleClickScrollTo = () => {
  document.getElementById('answer')?.scrollIntoView()
}
const handleClickSubmit = async () => {
  if (!id) {
    return ElMessage({
      message: '获取详情ID失败',
      type: 'error',
      duration: 2 * 1000
    })
  }
  try {
    answerLoadingBtn.value = true
    const res: any = await answerQuestion({
      faqId: id,
      content: contents.value
    })
    if (res) {
      ElMessage({
        message: '发布成功',
        type: 'success',
        duration: 2 * 1000
      })
      // 赋空字符串清空
      contents.value = ''
      radio1.value = '默认'
      isRequestSearchValueGetAnswerData()
    }
  } finally {
    answerLoadingBtn.value = false
  }
}
const handleCurrentChange = (val: number) => {
  searchParams.pageNum = val
  isRequestSearchValueGetAnswerData()
}
const handleChangeRadio = () => {
  searchParams.pageNum = 1
  isRequestSearchValueGetAnswerData()
}
const isRequestSearchValueGetAnswerData = () => {
  if (radio1.value === '最新') {
    getFaqDetailAnswerData({ searchValue: 1 })
  } else {
    getFaqDetailAnswerData()
  }
}
// 采纳回答
const handleClickLikeAnswer = async (answerId: number, id: string) => {
  try {
    likeLading.value = true
    const res: any = await likeAnswer({
      answerId,
      id
    })
    if (res) {
      ElMessage({
        message: '采纳成功',
        type: 'success',
        duration: 2 * 1000
      })
      getFaqDetailData()
      isRequestSearchValueGetAnswerData()
    }
  } finally {
    likeLading.value = false
  }
}
const getLikeTopData = async () => {
  try {
    topLoading.value = true
    const { data }: any = await getLikeTop()
    topData.value = data
  } finally {
    topLoading.value = false
  }
}
const handleClickToUserBlog = (userId: number | string) => {
  router.push({
    name: 'user-blog',
    params: {
      id: userId
    }
  })
}
const handleClickFollow = async (status: number, followedUserId: number) => {
  try {
    fllowbtnLoading.value = true
    const res: any = await followUser({
      followedUserId,
      status
    })
    if (res) {
      if (status === 1) {
        ElMessage({
          message: '取关成功',
          type: 'success',
          duration: 2 * 1000
        })
      } else {
        ElMessage({
          message: '关注成功',
          type: 'success',
          duration: 2 * 1000
        })
      }
      getFaqDetailData()
    }
  } finally {
    fllowbtnLoading.value = false
  }
}
onMounted(() => {
  getFaqDetailData()
  isRequestSearchValueGetAnswerData()
  getLikeTopData()
})
</script>

<style scoped lang="scss">
// @import '@/assets/style/reset.scss';
@import './index.scss';

:deep(img) {
  max-width: 100%;
}
</style>
